package shujujiegou.lianbiao;

import java.util.Iterator;
import java.util.function.Consumer;

public class SinglyLinkedList implements Iterable<Integer> {
    private Node head;//头指针

    //定义节点类
    private static class Node {
        int value;//值
        Node next;//下一个节点指向

        public Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    }

    //向链表头中添加元素
    public void addFirst(int value) {
        //链表为空
        // head = new Node(value, head);
        //链表非空
        head = new Node(value, head);
    }

    //遍历链表--利用泛型参数
    public void loop(Consumer<Integer> consumer) {
        Node p;
        p = head;
        while (p != null) {
            consumer.accept(p.value);
            p = p.next;
        }
    }

    //利用迭代器遍历
    @Override
    public Iterator<Integer> iterator() {
        return new NodeIterator();
    }

    private class NodeIterator implements Iterator<Integer> {
        Node p = head;

        @Override
        public boolean hasNext() {

            return p != null;
        }

        @Override
        public Integer next() {
            int value = p.value;
            p = p.next;
            return value;
        }
    }

    public void addLast(int value) {
        Node last = findLast();
        if (last == null) {
            addFirst(value);
            return;
        }
        last.next = new Node(value, null);
    }

    /*循环遍历到最后一个节点*/
    private Node findLast() {
        if (head == null) {
            return null;
        }
        Node p;
        for (p = head; p.next != null; p = p.next) {

        }
        return p;
    }
    //利用索引查找元素
    public int get(int index) {
        Node node = findNode(index);
        if (node == null) {
            throw new IllegalArgumentException(
                    String.format("index[%d]不合法%n", index)
            );
        }
        return node.value;
    }

    private Node findNode(int index) {
        Node p;
        int i = 0;
        for (p = head; p.next != null; p = p.next, i++) {
            if (i == index) {
                return p;
            }
        }
        return null;
    }

    //根据索引插入元素
    public void insert(int index,int value) {
        int i = index - 1;
        if (index==0){
            addFirst(value);
            return;
        }
        Node preNode = findNode(i);
        if (preNode==null){
            throw new IllegalArgumentException(
                    String.format("index[%d]不合法%n", index)
            );
        }
        preNode.next=new Node(value,preNode.next);
    }

    //删除第一个节点
    public void removedFirst(){
        if (head==null){
            throw new IllegalArgumentException(
                    String.format("index[%d]不合法%n", 0)
            );
        }
        head=head.next;
    }
}

